package handlers

import (
	"net/http"
	"qimo_work/repositories"
	"strconv"

	"github.com/gin-gonic/gin"
)

// SearchPostsHandler 文章搜索
func SearchPostsHandler(c *gin.Context) {
	// 创建新的 PostRepository 实例
	repo := repositories.NewPostRepository()

	// 获取搜索关键词
	title := c.DefaultQuery("title", "")
	categoryID, _ := strconv.Atoi(c.DefaultQuery("category_id", "0"))

	// 获取分页参数
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err != nil || pageSize < 1 {
		pageSize = 10
	}

	// 查询文章
	posts, total, err := repo.SearchPosts(title, uint(categoryID), page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "搜索失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":  "搜索成功",
		"posts":    posts,
		"page":     page,
		"pageSize": pageSize,
		"total":    total, // 返回总数
	})
}
